import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/event_bus_util.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';

class MaterialTypePage extends StatefulWidget {
  final Map arguments;

  MaterialTypePage({Key key, this.arguments}) : super(key: key);

  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<MaterialTypePage> {
  List materialList = [[], [], [], []];
  List selectList = [
    {'id': 0, 'name': '请选择', 'show': true},
    {'id': 0, 'name': '', 'show': false},
    {'id': 0, 'name': '', 'show': false},
    {'id': 0, 'name': '', 'show': false}
  ];
  int selectMenuIndex = -1;

  var eventBus = new EventBus();

  @override
  void initState() {
    super.initState();
    getMaterialType();
  }

  // 获取物资类型
  getMaterialType() {
    var api = 'goods/TypeAddInstall';

    // 报废清点物资分类
    if (widget.arguments['baseApi'] == 'scrap_enter/' ||
        widget.arguments['baseApi'] == 'allocate_enter/') {
      api = 'goods/TypeAddInstalls';
    }

    Utils.getUserId().then((userId) => {
          DioUtils.request(api, context: context, method: "POST",
              onSuccess: (res) {
            if (res['code'] == 1) {
              setState(() {
                materialList[0] = res['data']['parent'];
              });
            } else {
              Utils.showText(text: res['msg']);
            }
          }, onError: (error) {})
        });
  }

  Widget _buildTypeHead() {
    List<Widget> widget = [];

    for (int i = 0; i < selectList.length; i++) {
      var item = selectList[i]['name'];
      widget.add(InkWell(
          onTap: () {
            if (item.toString().isNotEmpty) {
              setState(() {
                selectMenuIndex = i;
                selectList[i]['show'] = true;
              });

              for (int c = selectList.length - 1; c > i; c--) {
                setState(() {
                  selectList[c]['id'] = 0;
                  selectList[c]['name'] = '';
                  selectList[c]['show'] = false;
                });
              }
            }
          },
          child: Container(
              height: 50,
              padding: EdgeInsets.symmetric(horizontal: 15),
              alignment: Alignment.center,
              child: Text(item,
                  style: TextStyle(
                      color: Utils.hexToColor(
                          selectMenuIndex == i ? '#297CFF' : '#000000'),
                      fontWeight: selectMenuIndex == i
                          ? FontWeight.bold
                          : FontWeight.w500)))));
    }

    return Container(
      width: double.infinity,
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: widget,
        ),
      ),
    );
  }

  Widget _buildTypeMenu({int menuIndex, List list}) {
    if (selectList[menuIndex]['show']) {
      return Expanded(
          child: Container(
              width: double.infinity,
              color: Colors.white,
              padding: EdgeInsets.symmetric(horizontal: 15),
              child: ListView.builder(
                  itemCount: list.length,
                  padding: EdgeInsets.only(bottom: 60.w),
                  itemBuilder: (BuildContext context, int index) {
                    var item = list[index];

                    return InkWell(
                        onTap: () {
                          for (int i = 0; i < list.length; i++) {
                            var mate = list[i];
                            if (item['id'] == mate['id'] &&
                                item['children'] != null) {
                              setState(() {
                                materialList[menuIndex + 1] = item['children'];
                              });

                              for (int x = 0; x <= menuIndex; x++) {
                                setState(() {
                                  selectList[x]['show'] = false;
                                });
                              }

                              setState(() {
                                selectList[menuIndex + 1]['show'] = true;
                              });

                              break;
                            }
                          }
                          setState(() {
                            selectMenuIndex = menuIndex;
                            selectList[menuIndex]['id'] = item['id'];
                            selectList[menuIndex]['name'] = item['type_name'];
                          });

                          confirmSelection();
                        },
                        child: Container(
                            width: 500.w,
                            height: 50,
                            alignment: Alignment.centerLeft,
                            decoration: BoxDecoration(
                                border: Border(
                                    bottom: BorderSide(
                                        width: 1,
                                        color: Utils.hexToColor('#F4F4F4')))),
                            child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text(item['type_name']),
                                  Offstage(
                                    offstage:
                                        item['children'] != null ? false : true,
                                    child: Image.asset('assets/arrow_r_n.png',
                                        width: 5),
                                  )
                                ])));
                  })));
    } else {
      return Container();
    }
  }

  confirmSelection() {
    Map selected;

    for (int i = selectList.length - 1; i >= 0; i--) {
      var item = selectList[i];

      if (item['name'].toString().isNotEmpty) {
        selected = item;
        break;
      }
    }

    eventBus.emit('enter_mct', {'select': selected});
    // Navigator.of(context).pop();
  }

  Widget build(BuildContext content) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
        appBar: TopBar(
          title: '选择分类',
          actions: <Widget>[
            InkWell(
                onTap: () {
                  var item = selectList[1];

                  if (item['name'].toString().isEmpty) {
                    Utils.showText(text: '请选择二级分类', align: Alignment(0, 0));
                    return;
                  }

                  Navigator.of(context).pop();
                },
                child: Container(
                  width: 50,
                  alignment: Alignment.center,
                  child: Text('确定'),
                ))
          ],
        ),
        body: Container(
            color: Colors.white,
            child: Column(children: <Widget>[
              _buildTypeHead(),
              _buildTypeMenu(menuIndex: 0, list: materialList[0]),
              _buildTypeMenu(menuIndex: 1, list: materialList[1]),
              _buildTypeMenu(menuIndex: 2, list: materialList[2]),
              _buildTypeMenu(menuIndex: 3, list: materialList[3]),
            ])));
  }
}
